<template>
  <div class="voice-management">
    <div class="page-header">
      <h1 class="page-title">
        <Volume2 :size="24" style="margin-right: 12px;" />
        音色管理
      </h1>
      <p class="page-description">管理系统中的语音音色配置</p>
    </div>

    <div class="content-area">
      <a-card title="音色列表" :bordered="false">
        <template #extra>
          <a-space>
            <a-button @click="loadVoiceList" :loading="loading">
              <RefreshCw :size="16" style="margin-right: 4px;" />
              刷新
            </a-button>
            <a-button type="primary" @click="handleAddVoice">
              <Plus :size="16" style="margin-right: 4px;" />
              添加音色
            </a-button>
          </a-space>
        </template>

        <a-table
          :columns="columns"
          :data-source="voiceList"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'type'">
              <a-tag :color="record.type === 0 ? 'pink' : 'blue'">
                {{ record.type === 0 ? '女声' : '男声' }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'createdAt'">
              {{ record.createdAt ? record.createdAt.replace('T', ' ').split('.')[0] : '-' }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  danger
                  @click="handleToggleStatus(record)"
                >
                  删除
                </a-button>
                <a-button type="link" size="small" @click="handleTest(record)">
                  试听
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 新增/编辑弹窗 -->
    <VoiceFormModal
      v-model:visible="formModalVisible"
      :is-edit="isEdit"
      :edit-data="currentVoice"
      @success="handleModalSuccess"
    />

    <!-- 删除确认弹窗 -->
    <VoiceDeleteModal
      v-model:visible="deleteModalVisible"
      :voice-data="currentVoice"
      @success="handleModalSuccess"
    />

    <!-- 状态切换弹窗 -->
    <VoiceStatusModal
      v-model:visible="statusModalVisible"
      :voice-data="currentVoice"
      @success="handleModalSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { Volume2, Plus, RefreshCw } from 'lucide-vue-next'
import { message } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import { VoiceFormModal, VoiceDeleteModal, VoiceStatusModal } from '@/components/VoiceManager'
import { Codewin } from '@/api/generated/Codewin'
import type { VoiceVo, VoiceDetailVo, VoicePageSearchDto } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores'

// API实例
const authStore = useAuthStore()
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: () => ({
    headers: authStore.token ? { Authorization: `Bearer ${authStore.token}` } : {}
  })
})

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 180,
  },
  {
    title: '音色名称',
    dataIndex: 'voiceName',
    key: 'voiceName',
  },
  {
    title: '音色类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 240,
  },
  {
    title: '操作',
    key: 'action',
    width: 240,
    fixed: 'right',
  },
]

// 数据状态
const loading = ref(false)
const voiceList = ref<VoiceVo[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 弹窗状态
const formModalVisible = ref(false)
const deleteModalVisible = ref(false)
const statusModalVisible = ref(false)
const isEdit = ref(false)
const currentVoice = ref<VoiceDetailVo | null>(null)

// 加载音色列表
const loadVoiceList = async () => {
  try {
    loading.value = true

    const response = await api.request({
      path: '/codewin/voice/list/admin',
      method: 'GET',
      query: {
        pageNo: pagination.current,
        pageSize: pagination.pageSize
      },
      headers: authStore.token ? { Authorization: `Bearer ${authStore.token}` } : {},
      secure: true
    })

    if (response.data?.code === 0 && response.data.data) {
      voiceList.value = response.data.data.list || []
      pagination.total = response.data.data.total || 0
    } else {
      message.error(response.data?.message || '获取音色列表失败')
    }
  } catch (error) {
    console.error('获取音色列表失败:', error)
    message.error('获取音色列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange: TableProps['onChange'] = (paginationInfo) => {
  if (paginationInfo) {
    pagination.current = paginationInfo.current || 1
    pagination.pageSize = paginationInfo.pageSize || 10
    loadVoiceList()
  }
}

// 获取音色详情
const getVoiceDetail = async (id: string): Promise<VoiceDetailVo | null> => {
  try {
    const response = await api.getVoice(id)
    if (response.data?.code === 0 && response.data.data) {
      return response.data.data
    } else {
      message.error(response.data?.message || '获取音色详情失败')
      return null
    }
  } catch (error) {
    console.error('获取音色详情失败:', error)
    message.error('获取音色详情失败')
    return null
  }
}

// 处理添加音色
const handleAddVoice = () => {
  isEdit.value = false
  currentVoice.value = null
  formModalVisible.value = true
}

// 处理编辑
const handleEdit = async (record: VoiceVo) => {
  if (!record.id) {
    message.error('音色信息不完整')
    return
  }

  const voiceDetail = await getVoiceDetail(record.id)
  if (voiceDetail) {
    isEdit.value = true
    currentVoice.value = voiceDetail
    formModalVisible.value = true
  }
}

// 处理状态切换
const handleToggleStatus = async (record: VoiceVo) => {
  if (!record.id) {
    message.error('音色信息不完整')
    return
  }

  const voiceDetail = await getVoiceDetail(record.id)
  if (voiceDetail) {
    currentVoice.value = voiceDetail
    statusModalVisible.value = true
  }
}

// 处理试听
const handleTest = async (record: VoiceVo) => {
  if (!record.id) {
    message.error('音色信息不完整')
    return
  }

  try {
    // 首先检查列表中是否已有音色文件URL
    if (record.voiceFileUrl) {
      window.open(record.voiceFileUrl, '_blank')
      return
    }

    // 如果列表中没有URL，获取音色详情
    const voiceDetail = await getVoiceDetail(record.id)
    if (voiceDetail?.voiceFileUrl) {
      // 如果有音色文件URL，在新窗口打开
      window.open(voiceDetail.voiceFileUrl, '_blank')
    } else {
      message.warning(`音色 "${record.voiceName}" 暂无音频文件可试听`)
    }
  } catch (error) {
    console.error('获取音色详情失败:', error)
    message.error(`试听音色 "${record.voiceName}" 失败，请重试`)
  }
}

// 处理删除
const handleDelete = async (record: VoiceVo) => {
  if (!record.id) {
    message.error('音色信息不完整')
    return
  }

  const voiceDetail = await getVoiceDetail(record.id)
  if (voiceDetail) {
    currentVoice.value = voiceDetail
    deleteModalVisible.value = true
  }
}

// 弹窗操作成功回调
const handleModalSuccess = () => {
  loadVoiceList()
}

// 组件挂载时加载数据
onMounted(() => {
  loadVoiceList()
})
</script>

<style scoped>
.voice-management {
  height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content-area {
  height: calc(100% - 100px);
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 16px;
}

:deep(.ant-pagination) {
  margin-top: 16px;
  text-align: right;
}
</style>
